package com.thd.springboot.framework.utils;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES加密
 *
 * @author lilong
 * @date 2017年7月5日 下午4:07:31
 */
public class AESUtils {

    private static String TRANSFORMATION = "AES/ECB/PKCS5Padding";
    private static String CHARSETNAME = "UTF-8";
    private static String ALGORITHM = "AES";

    public static String encrypt(String strKey, String strIn) throws Exception {
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, getKey(strKey));
        byte[] encrypted = cipher.doFinal(strIn.getBytes(CHARSETNAME));
        return Base64.encodeBase64String(encrypted);
    }

    public static String decrypt(String strKey, String strIn) throws Exception {
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.DECRYPT_MODE, getKey(strKey));
        byte[] original = cipher.doFinal(Base64.decodeBase64(strIn));
        return new String(original, CHARSETNAME);
    }

    private static SecretKeySpec getKey(String strKey) throws Exception {
        return new SecretKeySpec(strKey.getBytes(), ALGORITHM);
    }

    public static byte[] encrypt(byte[] content, byte[] password, String algorithm) {
        try {
            if (StringUtils.isBlank(algorithm)) {
                algorithm = TRANSFORMATION;
            }
            Cipher cipher = Cipher.getInstance(algorithm);
            ;
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(password, "AES"));
            return cipher.doFinal(content);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static byte[] decrypt(byte[] content, byte[] password, String algorithm) {
        try {
            if (StringUtils.isBlank(algorithm)) {
                algorithm = TRANSFORMATION;
            }
            Cipher cipher = Cipher.getInstance(algorithm);
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(password, "AES"));
            byte[] bytes = cipher.doFinal(content);
            return bytes;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
